/*
* EMRegion 东月地区选择插件
* @ jQuery v1.9.1
*
* Licensed under the Apache v2
* 
* usage as:
*   $(select).EMRegion({....});
*
* Fujian Eastmoonsoft
* @海眸1990/垚/迎风之叶
*/






(function ($) {
    //Extend Begin
    $.extend($.fn, {
        ///<summary>
        /// 东月地区选择插件
        ///</summary>
        EMRegion: function (setting) {
            var ps = $.extend({
                //触发提示的值
                AutoCompleteTrigger: 2,
                //自动完成数据
                AutoCompleteData: "",
                //选择面板
                SelectPanelData: "",
                //请求类型
                RequestType: "json",
                //InputKey
                InputKey: "input",
                //延迟时间
                Delay: 200,
                //常用区域
                CommonRegion: null
            },
            setting);

            var _obj = this;
            _obj = $(this);

            var _rawObj = _obj;





            function newGuid() {
                var guid = "";
                for (var i = 1; i <= 32; i++) {
                    var n = Math.floor(Math.random() * 16.0).toString(16);
                    guid += n;
                    if ((i == 8) || (i == 12) || (i == 16) || (i == 20))
                        guid += "-";
                }
                return guid;
            }


            var _id = newGuid(); //Math.random().toString().replace("0.", "");

            //自动完成类开始
            var AutoComplete = {
                Init: function () {
                    this.BoxID = Math.random().toString().replace("0.", "");
                    this.AutoCompleteBox = this.GenerateBox();
                    this.AutoCompleteBox.attr("ID", this.BoxID);
                    $("body").append(this.AutoCompleteBox);
                },
                BoxID: null,
                //盒标识
                AutoCompleteBox: null,
                //盒子对象
                delayHandle: null,
                //自动完成Ajax延迟句柄
                Close: function () { //关闭对象
                    this.AutoCompleteBox.remove();
                    this.AutoCompleteBox = null;
                },
                IsHide: function () {
                    if (this.AutoCompleteBox == null) {
                        return true;
                    }
                    return this.AutoCompleteBox.is(":hidden");
                },

                //选下一个
                ChooseNext: function (e) {
                    var o = this.AutoCompleteBox.children(".h");

                    //没有选择任何元素
                    if (o.length == 0) {
                        $(this.AutoCompleteBox.children()[1]).addClass("h");
                        return false;
                    }

                    //移除当前选择
                    $(o[0]).removeClass("h");

                    //移动到下一个元素
                    var n = $(o[0]).next();

                    //没有下一个了
                    if (n[0] == undefined) {
                        $(this.AutoCompleteBox.children()[1]).addClass("h");
                        return false;
                    }
                    n.addClass("h");
                    return false;
                },

                //选择上一个
                ChoosePreviou: function (e) {
                    var eleCount = this.AutoCompleteBox.children().length;
                    //console.log(eleCount);
                    //return 0;
                    var o = this.AutoCompleteBox.children(".h");

                    //没有选择任何元素
                    if (o.length == 0) {
                        $(this.AutoCompleteBox.children()[eleCount - 1]).addClass("h");
                        return false;
                    }

                    //移除当前选择
                    $(o[0]).removeClass("h");

                    //移动到上一个元素
                    var n = $(o[0]).prev();

                    //没有上一个了
                    if (n[0] == undefined) {
                        $(this.AutoCompleteBox.children()[eleCount - 1]).addClass("h");
                        return false;
                    }

                    if ($(n[0]).attr("class") == "cur") {
                        $(this.AutoCompleteBox.children()[eleCount - 1]).addClass("h");
                        return false;
                    }

                    n.addClass("h");
                    return false;

                },

                //清除对象内的元素
                ClearBox: function () {
                    this.AutoCompleteBox.children().each(function (index, domEle) {
                        if ($(domEle).attr("class") != "cur") {
                            $(domEle).remove();
                        }
                    });
                },

                //重新绑定数据
                RebindData: function (box, data) {
                    for (var _r in data) {
                        var _g = $("<li title=\"" + data[_r].ID + "\">" + data[_r].FullName + "</li>");
                        box.append(_g);
                        _g.bind("mouseenter", this.MouseenterBoxLine);
                        _g.bind("mouseleave", this.MouseleaveBoxLine);
                        _g.bind("click", this.ChooseClick);
                    }
                },

                //选择当前
                Choose: function (e) {

                    var o = this.AutoCompleteBox.children(".h");
                    if (o.length != 0) {
                        _obj.val(o[0].innerHTML);
                        var id = $(o[0]).attr("title");

                        _rawObj.val(id);
                        //
                    }

                    this.Close();
                },
                ChooseClick: function () {
                    _obj.val($(this).html());
                    _rawObj.val($(this).attr("title"));
                    AutoComplete.Close();
                },

                MouseenterBoxLine: function (e) {
                    $(this).parent().children().removeClass("h");
                    $(this).addClass("h");
                },
                MouseleaveBoxLine: function (e) {
                    $(this).removeClass("h");
                },
                //请求数据
                RequestData: function (data, callback) {
                    $.ajax({
                        type: "get",
                        url: ps.AutoCompleteData,
                        data: data,
                        dataType: ps.RequestType,
                        cache: true,
                        //jsonp: "callback",
                        jsonpCallback: "jsonpCallback",
                        success: callback
                    });
                },

                //生成自动完成框框
                GenerateBox: function () {
                    var bbb = "<div style='border:#CCC 1px solid;'><li class='cur'>可以使用光标键选择</li></div>";
                    bbb = $(bbb);
                    bbb.addClass("emselect");
                    bbb.css({
                        "position": "absolute",
                        "cursor": "pointer",
                        "width": "200px",
                        "background-color": "#FFF"
                    }).hide();
                    return bbb;
                },

                //加载或者填充自动完成对话框
                Show: function (e) {
                    if (this.AutoCompleteBox == null) {
                        this.Init();
                    }

                    //--Show Start
                    if (this.delayHandle != null) {
                        clearTimeout(this.delayHandle);
                    }

                    if (_obj.val().length >= ps.AutoCompleteTrigger) {
                        var _bbb = this.AutoCompleteBox;
                        var _t = this;

                        this.delayHandle = setTimeout(function () {
                            var sendData = "{'" + ps.InputKey + "':'" + _obj.val() + "'}";
                            sendData = eval('(' + sendData + ')');
                            _t.RequestData(sendData,
                            function (data) {
                                //------------------------------
                                _t.ClearBox();
                                if (data.length == 0) {
                                    _bbb.hide(300);
                                } else {
                                    _t.RebindData(_bbb, data);

                                    _bbb.css("top", _obj.offset().top + _obj.height() + 10).css("left", _obj.offset().left).show(300);
                                }
                                //------------------------------
                            });
                        },
                        ps.Delay);
                        //console.log(_obj.val());
                    } else {
                        this.AutoCompleteBox.hide(300);
                    }
                    //--Show End
                }
            };
            //自动完成类结束
            //地区选择开始
            var SelectPanel = {
                SelectPanelBox: null,
                //隐藏加载动画
                HideLoding: function () {
                    if (this.SelectPanelBox != null) {
                        this.SelectPanelBox.children("div.tabCon").children("img").hide();

                    }
                },
                //显示加载动画
                ShowLoding: function () {
                    if (this.SelectPanelBox != null) {
                        this.SelectPanelBox.children("div.tabCon").children("img").show(120);
                    }
                },
                //初始化
                Init: function (bindClickTab, bindClick) {
                    if (this.SelectPanelBox == null) {
                        this.SelectPanelBox = this.GenerateBox(bindClickTab, bindClick);
                    }
                },

                //生成盒子
                GenerateBox: function (bindClickTab, bindClickElement) {
                    var _b = $("<div></div>").css({
                        "position": "absolute"
                    }); //.hide();
                    _b.addClass("emrtab");
                    var _bb = $("<div class='tabList'></div>");
                    var _bp = $("<ul></ul>");
                    var _cy = $("<li class='cur'>常用</li>");
                    _cy.bind("click", bindClickTab);
                    _bp.append(_cy);
                    _cy = $("<li>省</li>");
                    _cy.bind("click", bindClickTab);
                    _bp.append(_cy);
                    _cy = $("<li>市</li>");
                    _cy.bind("click", bindClickTab);
                    _bp.append(_cy);
                    _cy = $("<li>区县</li>");
                    _cy.bind("click", bindClickTab);
                    _bp.append(_cy);
                    _bb.append(_bp);
                    _b.append(_bb);
                    var _tabCon = $("<div></div>").addClass("tabCon");
                    var _loding = $("<img style=\"height:16px; width:16px; margin:0 auto; text-align:center; margin:10px 0px 0px 10px; \"  />").hide();
                    _loding.attr("src", "");
                    _tabCon.append(_loding);

                    _tabCon.append(SelectPanel.DataConvertToElement(ps.CommonRegion, false, bindClickElement).addClass("_cyp"));
                    //this.HideLoding();
                    _b.append(_tabCon);
                    //
                    return _b;
                },

                //数据转换为元素
                DataConvertToElement: function (data, isParent, bindClick) {
                    if (isParent == undefined || isParent == null) {
                        isParent = false;
                    }
                    var _cyp = $("<div></div>").css({
                        "padding-top": "10px"
                    });
                    var _ul = $("<ul></ul>");
                    for (var _d in data) {
                        var _li = $("<li></li>");
                        _li.attr("FullName", data[_d].FullName == undefined ? data[_d].Name : data[_d].FullName);
                        _li.attr("title", data[_d].ID);
                        if (!isParent) {
                            _li.addClass("_eMc");
                        }
                        _li.append($("<a>" + data[_d].Name + "</a>"));
                        _ul.append(_li);

                        if (bindClick != undefined) {
                            _li.bind("click", bindClick);
                        }
                    }
                    _cyp.append(_ul);
                    return _cyp;

                },

                AjaxLoadData: function (parentID, callBack) {

                    var sendData = null;

                    if (parentID != undefined && parentID != null) {
                        sendData = "{'" + ps.SelectParentKey + "':'" + parentID + "'}";
                        sendData = eval('(' + sendData + ')');
                    }

                    //console.log(sendData);
                    $.ajax({
                        type: "get",
                        url: ps.SelectPanelData,
                        data: sendData,
                        dataType: ps.RequestType,
                        cache: true,
                        //jsonp: "callback",
                        jsonpCallback: "jsonpCallback",
                        success: callBack
                    });

                }

            };

            var SelectPanelEvent = {
                //关闭面板
                Close: function (e) {

                    if (SelectPanel.SelectPanelBox != null) {

                        SelectPanel.SelectPanelBox.hide();
                    }
                    //SelectPanel.SelectPanelBox.remove();
                    //SelectPanel.SelectPanelBox = null;
                },

                //销毁面板
                DisposePanel: function () {
                    SelectPanel.SelectPanelBox.hide();
                    SelectPanel.SelectPanelBox.remove();
                    SelectPanel.SelectPanelBox = null;
                },

                //点击选项卡
                ClickTab: function (e) {
                    var tabs = SelectPanel.SelectPanelBox.children(".tabList").children("ul").children("li");
                    tabs.removeClass("cur");
                    $(this).addClass("cur");

                    var tabContent = SelectPanel.SelectPanelBox.children(".tabCon"); //
                    tabContent.children("div").hide();
                    SelectPanel.ShowLoding();

                    var tabName = $(this).html();
                    if (tabName == "常用") {
                        SelectPanel.HideLoding();
                        tabContent.children("._cyp").show();
                    } else if (tabName == "省") {
                        if (tabContent.children("._pp") != 0) {
                            SelectPanel.AjaxLoadData(null,
                            function (data) {
                                SelectPanel.HideLoding();
                                var ele = SelectPanel.DataConvertToElement(data, true, SelectPanelEvent.ClickElement).addClass("_pp");
                                tabContent.append(ele);
                            });
                        } else {
                            tabContent.children("._pp").show();
                        }
                    } else if (tabName == "市") {
                        SelectPanel.HideLoding();
                        if (tabContent.children("._city") != 0) {
                            tabContent.children("._city").show();
                        }
                    } else if (tabName == "区县") {
                        SelectPanel.HideLoding();
                        if (tabContent.children("._county") != 0) {
                            tabContent.children("._county").show();
                        }
                    }

                    return false;
                },

                //点击元素
                ClickElement: function (e) {
                    //console.log("e");
                    var clickObj = $(this);
                    var tabContent = SelectPanel.SelectPanelBox.children(".tabCon");
                    var id = $(this).attr("title");
                    var tabs = SelectPanel.SelectPanelBox.children(".tabList").children("ul").children("li");


                    _obj.val($(this).attr("FullName"));
                    _rawObj.val(id);

                    if ($(this).hasClass("_eMc")) { //最后一级的对象，直接进行选择

                        SelectPanelEvent.Close();
                        return false;
                    } else { //创建下一级
                        //SelectPanel
                        SelectPanel.AjaxLoadData(id,
                        function (data) {
                            if (data.length == 0) {
                                // _obj.val(clickObj.attr("FullName"));
                                //_rawObj.val(id);
                                SelectPanelEvent.Close();
                                return;
                            }
                            SelectPanel.HideLoding();
                            tabContent.children().hide();


                            //确定级别
                            var ele = SelectPanel.DataConvertToElement(data, true, SelectPanelEvent.ClickElement); //.addClass("_pp");
                            var pc = clickObj.parent().parent();

                            if (pc.hasClass("_pp")) {

                                ele.addClass("_city");
                                tabContent.children("._city").remove();

                                tabs.removeClass("cur");
                                $(tabs[2]).addClass("cur");


                            } else if (pc.hasClass("_city")) {

                                ele.addClass("_county");
                                tabContent.children("._county").remove();

                                tabs.removeClass("cur");
                                $(tabs[3]).addClass("cur");

                            }



                            tabContent.append(ele);
                        });



                        return false;
                        //console.log("下一级");
                    }
                },

                //显示面板
                Show: function (e) {

                    //.Close();
                    if (AutoComplete.AutoCompleteBox != null) {
                        AutoComplete.AutoCompleteBox.remove();
                        AutoComplete.AutoCompleteBox = null;
                    }

                    if (SelectPanel.SelectPanelBox == null) {
                        SelectPanel.Init(SelectPanelEvent.ClickTab, SelectPanelEvent.ClickElement);
                        $("body").append(SelectPanel.SelectPanelBox);
                    }

                    $("body").bind("click", function () {

                        SelectPanel.SelectPanelBox.hide();

                    })

                    SelectPanel.SelectPanelBox.css("top", _obj.offset().top + _obj.height() + 10).css("left", _obj.offset().left).show(300);


                    return false;

                }
            };




            //地区选择结束
            var Route = {
                KeyUp: function (e) {

                    SelectPanelEvent.Close();
                    if (AutoComplete.IsHide()) {
                        return AutoComplete.Show(e);
                    } else {
                        switch (e.keyCode) {
                            case 38:
                                return AutoComplete.ChoosePreviou(e);
                                break; // 上
                            case 40:
                                return AutoComplete.ChooseNext(e);
                                break; // 下
                            case 13:
                                return AutoComplete.Choose(e);
                                break; //回车
                            default:
                                return AutoComplete.Show(e);
                        }
                    }
                }
            }
            //路由
            var _obj2 = _obj.clone();
            _obj.hide();
            _obj.after(_obj2);
            _obj = _obj2;

            _obj.attr("id", _id);


            if (_obj.attr("name") != undefined) {
                var d = _obj.attr("name");
                _obj.attr("name", d + "_display");
            }

            _obj.bind("keyup", Route.KeyUp);
            _obj.bind("click", SelectPanelEvent.Show);



            return { Set: function (Value, Name) {

                _rawObj.val(Value);
                _obj.val(Name);

            }
            };

        }
    });
    //Extend End
})(jQuery);